package org.microdream.easy.deploy.action;

import com.alibaba.fastjson.JSONArray;
import ice.server.comm.BaseAction;
import ice.server.comm.GloubCode;
import ice.tool.ResultMap;
import ice.tool.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.microdream.easy.deploy.po.DFunction;
import org.microdream.easy.deploy.service.DFunctionService;
import org.microdream.easy.deploy.service.DSequenceService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/DFunction")
public class DFunctionAction extends BaseAction {

    @Resource
    private DFunctionService dFunctionService;
    @Resource
    private DSequenceService dSequenceService;

    /**
     * 权限树
     * */
    @GetMapping("getFunctionTree")
    public JSONArray getFunctionTree(){
        JSONArray jsonArray = new JSONArray();
        jsonArray = dFunctionService.getOrgKeyValue("TESTRENT","myId","text");
        return jsonArray;
    }

    /**
     * 增加权限
     * */
    @PostMapping("")
    public Map add(DFunction dFunction){
        dFunction.setFunctionCode(dSequenceService.getNextSequence(GloubCode.FUNCTIONCODE.getName(),GloubCode.SUPPLEMENTCODE.getName()));
        dFunction.setIsLock(0);
        dFunction.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        return dFunctionService.add(dFunction);
    }

    /**
     * 修改权限
     * */
    @PutMapping("")
    public Map update(DFunction dFunction){
        DFunction dFunctionOld = dFunctionService.get(dFunction.getId());
        try {
            BeanUtil.copyNotEmptyProprties(dFunction,dFunctionOld);
            dFunctionOld.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        } catch (Exception e) {
            return ResultMap.build().warningState().message(e.getMessage()).get();
        }
        return dFunctionService.upd(dFunctionOld);
    }

    /**
     * 删除权限
     * */
    @DeleteMapping("/{key}")
    public Map delete(@PathVariable("key")String key){
        if(StringUtils.isEmpty(key)){
            return ResultMap.build().warningState().message("无效数据").get();
        }
        List<String> ids = Arrays.asList(key.split(","));
        return dFunctionService.del(ids);
    }

    /**
     * 查询单条权限
     * */
    @GetMapping("/{key}")
    public DFunction searchById(@PathVariable("key") Integer key){
        return dFunctionService.get(key);
    }

    @GetMapping("/searchByCode/{key}")
    public DFunction searchByCode(@PathVariable("key") String key){
        return dFunctionService.searchByCode(key);
    }
}
